<script setup lang="tsx">
import { reactive, ref, watch, onMounted } from 'vue'
import { Form, FormSchema } from '@/components/Form'
import { useI18n } from '@/hooks/web/useI18n'
import { useForm } from '@/hooks/web/useForm'
import { userLogin, getVerCodeSrc, checkIsVerCode } from '@/api/login'
import { useRouter } from 'vue-router'
import type { RouteLocationNormalizedLoaded } from 'vue-router'
import { UserLoginModel } from '@/api/login/types'
import { loginStateStoreWithOut } from '@/store/modules/loginState'
import { BaseButton } from '@/components/Button'
import { ElInput, ElImage, ElSpace, ElMessage } from 'element-plus'
import userPwdChange from '@/components/login/userPwdChange.vue'
import router from '@/router'
import { encryptPwd } from '@/utils/index'
const userStore = loginStateStoreWithOut()

const { currentRoute } = useRouter()

const { t } = useI18n()
const verSrc = ref<string>('')
const validatePassword = (rule, value, callback) => {
  if (value.length < 6) {
    callback(new Error(t('login.pwdLen')))
  } else {
    callback()
  }
}
const validateLoginName = (rule, value, callback) => {
  if (value == null || value === '') {
    callback(new Error(t('common.required')))
    return
  } else if (value.length < 6) {
    callback(new Error(t('login.usernameLen')))
  } else {
    callback()
  }
}
const rules = {
  LoginName: [{ required: true, trigger: 'blur', validator: validateLoginName }],
  LoginPwd: [{ required: true, trigger: 'blur', validator: validatePassword }],
  VerCode: [
    { required: true, trigger: 'blur', message: t('login.codeNull') },
    { min: 4, max: 4, trigger: 'blur', message: t('login.codeLen') }
  ]
}
const refreshCode = async function () {
  const formData = await getFormData<UserLoginModel>()
  const val = formData.LoginName
  if (val == null || val == '' || val.length < 6) {
    return
  }
  verSrc.value = getVerCodeSrc(val)
}
const checkIsVer = async (val) => {
  if (val == null || val == '' || val.length < 6) {
    return
  }
  const isVer = await checkIsVerCode(val)
  if (isVer) {
    showVerCode(val)
  } else {
    const index = schema.findIndex((c) => c.field == 'code')
    if (index !== -1) {
      schema.splice(index, 1)
    }
  }
}
const showVerCode = (val: string) => {
  if (schema.findIndex((a) => a.field == 'VerCode') !== -1) {
    verSrc.value = getVerCodeSrc(val)
    return
  }
  verSrc.value = getVerCodeSrc(val)
  schema.splice(3, 0, {
    field: 'VerCode',
    label: t('login.code'),
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: (formData) => {
          return (
            <ElSpace>
              <ElInput v-model={formData.VerCode} placeholder={t('login.codePlaceholder')} />
              <ElImage
                src={verSrc.value}
                style={{ cursor: 'pointer' }}
                onClick={refreshCode}
              ></ElImage>
            </ElSpace>
          )
        }
      }
    }
  })
}
const schema = reactive<FormSchema[]>([
  {
    field: 'title',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return <h2 class="text-2xl font-bold text-center w-[100%]">{t('login.login')}</h2>
        }
      }
    }
  },
  {
    field: 'LoginName',
    label: t('login.username'),
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: t('login.usernamePlaceholder'),
      on: {
        change: checkIsVer
      }
    }
  },
  {
    field: 'Password',
    label: t('login.password'),
    component: 'InputPassword',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      placeholder: t('login.passwordPlaceholder')
    }
  },
  {
    field: 'login',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="w-[100%]">
                <BaseButton
                  loading={loading.value}
                  type="primary"
                  class="w-[100%]"
                  onClick={signIn}
                >
                  {t('login.login')}
                </BaseButton>
              </div>
            </>
          )
        }
      }
    }
  }
])

const { formRegister, formMethods } = useForm()
const { getFormData, getElFormExpose } = formMethods

const loading = ref(false)

const redirect = ref<string>('')
const loginName = ref<string>('')
const visible = ref<boolean>(false)
onMounted(() => {
  //userStore.reset()
})
watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)
// 登录
const signIn = async () => {
  const formRef = await getElFormExpose()
  await formRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const formData = await getFormData<UserLoginModel>()
      const data = Object.assign({}, formData)
      data.Password = encryptPwd(data.Password)
      try {
        const res = await userLogin(data)
        userStore.setToken(res.AccreditId)
        router.replace({ name: 'Loading' })
      } catch (e) {
        if (e.param === 'verCode:true') {
          showVerCode(data.LoginName)
        } else if (e.errorcode === '205022731408005') {
          loginName.value = data.LoginName
          showVerCode(data.LoginName)
          visible.value = true
        } else if (e.errorcode === '204955529462405') {
          ElMessage.error('用户已锁定请' + e.param + '后重试!')
        }
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<template>
  <div>
    <Form
      :schema="schema"
      :rules="rules"
      label-position="top"
      hide-required-asterisk
      size="large"
      class="dark:(border-1 border-[var(--el-border-color)] border-solid)"
      @register="formRegister"
    />
    <userPwdChange :login-name="loginName" title="密码已过期请修改" v-model:visible="visible" />
  </div>
</template>
